﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Office;
using Extensions;
using MyDashBoardNS;
using System.Windows.Controls.Primitives;
using System.Collections;
using System.Configuration;
using System.Data;
using System.IO;
using System.Windows.Threading;

namespace Dashboard
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class _MyDashboard : Window
    {
        private DispatcherTimer timer;
        private string ActionMsg = "";

        public _MyDashboard()
        {
            InitializeComponent(); 
            titleBar.MouseLeftButtonDown += (o, e) => DragMove();

            Loaded += new RoutedEventHandler(Window1_Loaded);
            
        }

        void Window1_Loaded(object sender, RoutedEventArgs e)
        {
            //timer.AutoReset = false;
            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(1);
            timer.Tick += timer1_Tick;

            timer.Start();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            timer.Stop();
            LoadStartUpItems();

            //Extensions.AsynchronousSocketListener.StartListening();
        }

        private void LoadStartUpItems() 
        {
            if (Initialisation())
            {
                GetTaskBoardEntries();
                GetTaskHistory();
                GetSmartLibList();
                GetToDoNotes();
                LoadDefaults();
            }
            else {
                ShowStatusBarText(0, ActionMsg);
            }
        }

        private bool Initialisation() {
            bool _ = false;
            
            MyDashboardM objM = new MyDashboardM();
            _ = objM.DBValidation("");
            ActionMsg = objM.ActionMsg;

            return _;
        }
        
        private bool ValidationTaskBoardEntry()
        {
            bool status = true;

            if (!txtFromTime.Text.IsNotNullAndEmpty())
            {
                MessageBox.Show("hey you!!, dont try with empty start time buddy...");
                txtFromTime.Focus();
                status = false;
            }
            //else if (!txtToTime.Text.IsNotNullAndEmpty())
            //{
            //    MessageBox.Show("hey, dont forget to enter task completed time.");
            //}
            
            if (status && !txtTaskInfo.Text.IsNotNullAndEmpty())
            {
                MessageBox.Show("tel me wat u gonna do????");
                txtTaskInfo.Focus();
                status = false;
            }            

            return status;
        }

        private void CreateTaskBoardEntry() {

            MyDashboard obj = new MyDashboard();
            MyDashboardM objM = new MyDashboardM();

            if (dgTaskBoardList.SelectedItems.Count > 0)
            {
                DataRowView row = (DataRowView)dgTaskBoardList.SelectedItems[0];
                obj.TaskBoardEntryId = row[0].ToInt();
            }

            if (calOptions.SelectedDate != null && calOptions.SelectedDate != DateTime.MinValue)
                obj.Today = calOptions.SelectedDate.ToDateTime();
            else
                obj.Today = DateTime.Now;

            obj.FromTime = txtFromTime.Text;
            obj.ToTime = txtToTime.Text;
            obj.TaskBoardInfo = txtTaskInfo.Text;
            obj.Status = lstStatus.Text;

            if (objM.SaveTaskBoardDetails(obj))
            {
                ShowStatusBarText(0,"Task Board Entry Saved Successfully.");
                GetTaskBoardEntries();
                GetTaskHistory();
                txtFromTime.Text = "";
                txtToTime.Text = "";
                txtTaskInfo.Text = "";
                lstStatus.Text="New";
            }
            else {
                ShowStatusBarText(0, objM.ActionMsg);
            }
 
        }

        private void GetTaskBoardEntries()
        {
            MyDashboard obj = new MyDashboard();
            MyDashboardM objM = new MyDashboardM();

            if (calOptions.SelectedDate!=null && calOptions.SelectedDate != DateTime.MinValue)
                obj.Today = calOptions.SelectedDate.ToDateTime();
            else
                obj.Today = DateTime.Today;

            if (objM.GetTaskBoardEntryList(obj)) {
                dgTaskBoardList.ItemsSource = objM.dvData;

            }

        }

        private void GetTaskBoardEntrieDetails(int TaskBoardEntryId)
        {
            MyDashboard obj = new MyDashboard();
            MyDashboardM objM = new MyDashboardM();

            obj.TaskBoardEntryId = TaskBoardEntryId;

            if (objM.GetTaskBoardEntryList(obj))
            {
                DataView dv = objM.dvData;
                if (dv.Count > 0) {
                    txtFromTime.Text = dv[0]["TaskFromDate"].ToStringFromObject();
                    txtToTime.Text = dv[0]["TaskToDate"].ToStringFromObject();
                    txtTaskInfo.Text = dv[0]["TaskInfo"].ToStringFromObject();
                    lstStatus.SelectedValue = dv[0]["Status"].ToStringFromObject();
                }
            }

        }

        private void GetTaskHistory() 
        {             
            MyDashboard obj = new MyDashboard();
            MyDashboardM objM = new MyDashboardM();

            obj.StartTime = dtpichistoryfrom.SelectedDate;
            obj.EndTime = dtpichistoryto.SelectedDate;
            obj.SortColumn = "TaskFromDate";
            obj.SearchText = txtSearchInTaskHistory.Text;

            if (objM.GetTaskBoardEntryList(obj)) {
                dgHistory.ItemsSource = objM.dvData;
            }
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            if (ValidationTaskBoardEntry())
            {
                CreateTaskBoardEntry();
            }
        }

        private void btnNew_Click(object sender, RoutedEventArgs e)
        {
            txtFromTime.Text = "";
            txtToTime.Text = "";
            txtTaskInfo.Text = "";
            dgTaskBoardList.SelectedItems.Clear();
            lstStatus.Text = "New";
            ShowStatusBarText(0,"Ready For Adding New Task Entry");
        }

        private void ShowStatusBarText(int StatusBarItemIndex, string msg)
        {
            StatusBarItem item = (StatusBarItem)this.statusBar1.Items[StatusBarItemIndex];
            item.Content = msg;
        }

        private void dgTaskBoardList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                DataRowView row = (DataRowView)dgTaskBoardList.SelectedItems[0];

                txtFromTime.Text = row["TaskFromDate"].ToDateTime().ToString("hh:mm");
                if (row["TaskToDate"].IsNotNullAndEmpty())
                txtToTime.Text = row["TaskToDate"].ToDateTime().ToString("hh:mm");
                txtTaskInfo.Text = row["TaskInfo"].ToStringFromObject();
                //lstStatus.SelectedValuePath = "Name";
                //lstStatus.SelectedValue = row["Status"].ToStringFromObject();
                lstStatus.Text = row["Status"].ToStringFromObject();
            }
            catch { }
        }

        public IEnumerable<DataGridRow> GetDataGridRows(DataGrid grid)
        {
            var itemsSource = grid.ItemsSource as IEnumerable;
            if (null == itemsSource) yield return null;
            foreach (var item in itemsSource)
            {
                var row = grid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
                if (null != row) yield return row;
            }
        }

        private void SaveDashboardSettings() {

            Settings obj = new Settings();
            MyDashboardM objm = new MyDashboardM();
            obj.YourName = txtYourName.Text;
            obj.YourEmail = txtYourEmailId.Text;

            if (objm.SaveSettings(obj))
            {
                ShowStatusBarText(0, "Options Saved");
            }
            else {
                ShowStatusBarText(0, objm.ActionMsg);
            }

            //ConfigurationManager.AppSettings.Set("YourName",txtYourName.Text);
            //ConfigurationManager.AppSettings.Set("YourEmail",txtYourEmailId.Text);

            //System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            //config.AppSettings.Settings.Remove("YourName");
            //config.AppSettings.Settings.Add("YourName", txtYourName.Text);

            //config.AppSettings.Settings.Remove("YourEmail");
            //config.AppSettings.Settings.Add("YourEmail", txtYourEmailId.Text);

            //config.Save(ConfigurationSaveMode.Modified);
   
            //ConfigurationManager.RefreshSection("appSettings");

        }

        private void btnSaveSettings_Click(object sender, RoutedEventArgs e)
        {
            SaveDashboardSettings();
            LoadDefaults();
        }

        private void LoadDefaults() {
            try
            {
                Settings obj = new Settings();
                MyDashboardM objm = new MyDashboardM();

                if (objm.GetSettings(obj)) {
                    DataView dv = new DataView();
                    dv = objm.dvData;
                    dv.RowFilter = "[Column] in ('YourName','YourEmail')";
                    if (dv != null && dv.Count ==2)
                    {
                        txtYourName.Text = dv[0]["Value"].ToStringFromObject();
                        txtYourEmailId.Text = dv[1]["Value"].ToStringFromObject();

                        if (txtYourName.Text.IsNotNullAndEmpty())
                        {
                            txtblockTitle.Text = txtYourName.Text + "'s Dashboard";
                        }
                        else
                        {
                            txtblockTitle.Text = "My Dashboard";
                        }
                    }
                }
            }catch(Exception ex){
                ShowStatusBarText(0, ex.ToString());
            }

            if (calOptions.SelectedDate !=null && calOptions.SelectedDate != DateTime.MinValue)
                ShowStatusBarText(1, "Today: " + calOptions.SelectedDate.ToString());
            else
                ShowStatusBarText(1, "Today: " + DateTime.Now.Date.ToString(Declarations.DateFormat));

        }

        private void calOptions_SelectedDatesChanged(object sender, SelectionChangedEventArgs e)
        {
            GetTaskBoardEntries();
            ShowStatusBarText(1, "Today: " + calOptions.SelectedDate.ToDateTime().ToString(Declarations.DateFormat));
        }

        private bool CreateNewReminder() {
            bool status = false;
            try
            {
                Microsoft.Office.Interop.Outlook.Application outlookApp = new Microsoft.Office.Interop.Outlook.Application();
                Microsoft.Office.Interop.Outlook.AppointmentItem oAppointment = (Microsoft.Office.Interop.Outlook.AppointmentItem)outlookApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olAppointmentItem); // creates a new appointment
                oAppointment.Subject = txtTaskReminder.Text;
                oAppointment.Body = txtTaskReminder.Text;
                oAppointment.Location = "";

                oAppointment.Start = DateTime.Now;

                oAppointment.End = DateTime.Now.AddDays(2); // End date 
                oAppointment.ReminderSet = true; // Set the reminder
                oAppointment.ReminderMinutesBeforeStart = 15; // reminder time
                oAppointment.Importance = Microsoft.Office.Interop.Outlook.OlImportance.olImportanceHigh; // appointment importance
                oAppointment.BusyStatus = Microsoft.Office.Interop.Outlook.OlBusyStatus.olBusy;
                oAppointment.Save();

                lstReminders.Items.Add(txtTaskReminder.Text);
                ShowStatusBarText(0, "Reminder Added");
                txtTaskReminder.Text = "";
            }catch(Exception e){
                ShowStatusBarText(0, e.Message);
            }

            //Microsoft.Office.Interop.Outlook.MailItem mailItem = oAppointment.ForwardAsVcal(); 
            //// email address to send to 
            //mailItem.To = "mailto:me@decodedsolutions.co.uk";
            //// send 
            //mailItem.Send();

            return status;
        }

        private void txtTaskReminder_OnKeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                if (txtTaskReminder.Text.IsNotNullAndEmpty())
                {
                    ShowStatusBarText(0, "Creating Reminder...");
                    CreateNewReminder();
                }
                else {
                    MessageBox.Show("what to remind?");
                    txtTaskReminder.Focus();
                }
            }

        }        

        private void btnNewLib_Click(object sender, RoutedEventArgs e)
        {
            ClearLibrary();
            GetSmartLibList();
        }

        private void ClearLibrary() {
            TextRange range;
            range = new TextRange(rteLibrary.Document.ContentStart, rteLibrary.Document.ContentEnd);
            range.Text = "";
            txtSmartLibKeyword.Text = "";
            dgSmartLib.SelectedItems.Clear();
        }

        private void GetSmartLibList() {
            SmartLibrary obj = new SmartLibrary();
            SmartLibraryM objM = new SmartLibraryM();
            obj.Keywords = txtSmartLibKeyword.Text;

            if (objM.GetLibraryList(obj)) {
                dgSmartLib.ItemsSource = objM.dvData;
            }
        }

        private void btnSaveSmartLib_Click(object sender, RoutedEventArgs e)
        {
            SaveSmartLibrary();
        }

        private void SaveSmartLibrary() {
            TextRange range;
            range = new TextRange(rteLibrary.Document.ContentStart, rteLibrary.Document.ContentEnd);
            //range.Save(fStream, DataFormats.XamlPackage);

            if (txtSmartLibKeyword.Text.IsNotNullAndEmpty() && range.Text.IsNotNullAndEmpty())
            {
                SmartLibrary obj = new SmartLibrary();
                SmartLibraryM objM = new SmartLibraryM();

                obj.Keywords = txtSmartLibKeyword.Text;
                obj.Content = range.Text;

                if (dgSmartLib.SelectedItems.Count > 0)
                {
                    DataRowView row = (DataRowView)dgSmartLib.SelectedItems[0];
                    obj.LibraryRecordId = row[0].ToInt();
                }

                if (objM.SaveLibraryDetails(obj))
                {
                    ShowStatusBarText(0, "New entry added");
                    txtSmartLibKeyword.Text = "";
                    range.Text = "";
                    GetSmartLibList();
                }
                else
                {
                    ShowStatusBarText(0, objM.ActionMsg);
                }

            }
            else
            {
                MessageBox.Show("nothing to do dear!!!!....");
            }
        }

        private void txtSmartLibKeyword_KeyDowwn(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter) 
            {
            
                if (txtSmartLibKeyword.Text.IsNotNullAndEmpty())
                {
                    GetSmartLibList();                    
                }

            }
            else if (e.Key == Key.Escape) 
            {
                txtSmartLibKeyword.Text = "";
                GetSmartLibList();
            }
        }

        private void txtSearchInTaskHistory_KeyDowwn(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                if (txtSearchInTaskHistory.Text.IsNotNullAndEmpty())
                {
                    GetTaskHistory();
                }

            }
            else if (e.Key == Key.Escape)
            {
                txtSearchInTaskHistory.Text = "";
                GetTaskHistory();
            }
        }

        private void dgTaskBoardList_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            DataRowView item = e.Row.Item as DataRowView;
            if (item != null)
            {
                DataRow row = item.Row;
                if(row["Status"].IsInArray("completed"))
                    e.Row.Background = new SolidColorBrush(Colors.LightGreen);
                else if (row["Status"].IsInArray("Cancelled"))
                    e.Row.Background = new SolidColorBrush(Colors.Red);
                else if (row["Status"].IsInArray("Pending"))
                    e.Row.Background = new SolidColorBrush(Colors.LightYellow);
                else if (row["Status"].IsInArray("In-Progress"))
                    e.Row.Background = new SolidColorBrush(Colors.LightSkyBlue);
            }   
        }

        public void pastecontent()
        {
            tabControl1.SelectedItem = (TabItem)tabControl1.FindName("tabSmartLib");
            ClearLibrary();
            
            TextRange range;
            range = new TextRange(rteLibrary.Document.ContentStart, rteLibrary.Document.ContentEnd);
            range.Text = Clipboard.GetText();
            if (Clipboard.GetText().IsNotNullAndEmpty() && Clipboard.GetText().Length>0)
                txtSmartLibKeyword.Text = (Clipboard.GetText().Length>25?Clipboard.GetText().Substring(0, 25):Clipboard.GetText());

            if (range.Text.Length > 0 && txtSmartLibKeyword.Text.IsNotNullAndEmpty())
            {
                SaveSmartLibrary();
            }

        }

        private void dgSmartLib_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (dgSmartLib.SelectedItems.Count > 0)
                {
                    DataRowView row = (DataRowView)dgSmartLib.SelectedItems[0];
                    
                    txtSmartLibKeyword.Text = row["Keywords"].ToStringFromObject();

                    TextRange range;
                    range = new TextRange(rteLibrary.Document.ContentStart, rteLibrary.Document.ContentEnd);
                    range.Text = row["Content"].ToStringFromObject();
                }
            }
            catch (Exception ex){
                ShowStatusBarText(0,ex.ToString());
            }
        }

        #region[-- To Do --]
        
        private void SaveToDoNotes()
        {
            try {

                TextWriter tw = new StreamWriter("qwertyuiopasdfghjklzxcvbnm");

                tw.WriteLine(txtTodoNotes.Text);

                tw.Close();

            }catch(Exception ex){
                ShowStatusBarText(0,ex.ToString());
            }
        }

        private void GetToDoNotes() {
            try
            {
                if (File.Exists("qwertyuiopasdfghjklzxcvbnm"))
                {
                    StreamReader sr = new StreamReader("qwertyuiopasdfghjklzxcvbnm");
                    txtTodoNotes.Text = sr.ReadToEnd();
                    sr.Close();
                }
            }
            catch (Exception ex)
            {
                ShowStatusBarText(0, ex.ToString());
            }
        }

        #endregion

        #region[--Main Window Events--]
        void window_Activated(object sender, EventArgs e)
        {
            //ShowStatusBarText(0, "window_Activated");
        }

        void window_Deactivated(object sender, EventArgs e)
        {
            //ShowStatusBarText(0, "window_Deactivated");
        }

        private void Window_StateChanged(object sender, EventArgs e)
        {
            MessageBox.Show(this.WindowState.ToString());
            if (this.WindowState == System.Windows.WindowState.Minimized)
            {
                this.WindowState = System.Windows.WindowState.Maximized;
            }
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            SaveToDoNotes();
            ShowStatusBarText(0,"exiting... ");
        }
        #endregion

        private void btnValidateDB_Click(object sender, RoutedEventArgs e)
        {
            //MyDashboardM objm = new MyDashboardM();
            //objm.DBValidation(txtDBConString.Text);
        }

        private void tabControl1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (tabSmartLib != null && tabSmartLib.IsSelected)
            {
                this.Height = 500;
                tabControl1.Height = 400;
                grid1.Height = 500;
                rteLibrary.Height = 180;
                statusBar1.Margin = new Thickness(0, 456, 0, 0);
            }
            else if (tabSmartLib != null ){
                this.Height = 400;
                tabControl1.Height = 320;
                grid1.Height = 400;
                rteLibrary.Height = 90;
                statusBar1.Margin = new Thickness(0, 356, 0, 0);
            }
        
        }

        private void dtpichistoryfrom_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            GetTaskHistory();
        }

        private void dtpichistoryto_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            GetTaskHistory();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (tabMessaging != null) {
                tabMessaging.Visibility = Visibility.Collapsed;
            }
        }
         
    }
}
